package org.esk.dablog.web.forms;

import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.esk.dablog.service.EntryManager;
import org.esk.dablog.model.Entry;
import org.esk.dablog.web.util.RequestUtils;
import org.esk.dablog.web.functions.EntryFunctions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This base class is used to change Entry state
 * User: esk
 * Date: 09.12.2006
 * Time: 21:16:46
 * $Id:$
 */
public class ChangeEntryStateForm extends ParameterizableViewController {
    private EntryManager entryManager;
    private int newState;


    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        long id = RequestUtils.extractLongParameter(request);
        Entry e = entryManager.getEntry(Entry.class, id);
        if (EntryFunctions.isAllowedEditing(e, request.getRemoteUser()) &&
                isAllowedTransition(e.getState(), newState)) {
            e.setState(newState);
            entryManager.updateEntry(e);
        } else {
            //TODO throw exception??
        }
        return new ModelAndView(new RedirectView(getViewName() + "/" + e.getId()));
    }

    protected boolean isAllowedTransition(int oldState, int newState) {
        return true;
    }

    public void setNewState(int newState) {
        this.newState = newState;
    }

    public void setEntryManager(EntryManager entryManager) {
        this.entryManager = entryManager;
    }
}
